#!/bin/bash
# Author: fanyongfeng
# 0  1 * * * /bin/bash /root/script/mysql_data_backup.sh &>> /backup/mysql_data_backup/backup.log

# 设置管道中任意一个命令失败时都返回失败状态
set -o pipefail

TODAY=$(date +%Y%m%d)
DATA_BACKUP_DIR="/backup/pgsql_data_backup"
BASEDIR="/data/pgsql/11"
PGSQL_USER_INFO="/root/script/.pgsql_user_info"
[[ ! -f ${PGSQL_USER_INFO} ]] && echo "file not exist: ${PGSQL_USER_INFO}" && exit 1

USER=$(awk '{print $1}' ${PGSQL_USER_INFO})
PGPASSWORD=$(awk '{print $2}' ${PGSQL_USER_INFO})
DBNAME=iot
HOST_IP=$(/sbin/ip add| grep global | grep -E 'eth|bond0'  | awk '{print $2}'| awk -F / '{print $1}')

mkdir -p ${DATA_BACKUP_DIR}

${BASEDIR}/bin/pg_dump -h ${HOST_IP} -U ${USER} -p 5432 -d ${DBNAME} --if-exists -c -Ox | gzip > ${DATA_BACKUP_DIR}/${DBNAME}-${TODAY}.sql.gz
[ $? -eq 0 ] && echo "${TODAY} ${DBNAME} backup success" || echo "${TODAY} ${DBNAME} backup failed"

find ${DATA_BACKUP_DIR} -type f -mtime +7 | xargs -r -n 10 rm -f